<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestionsList"
      :key="index"
    >
      <div
        slot="title"
        v-html="highLight(text)"
        @click="$emit('search', text)"
      ></div>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: '',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestionsList: [],
      str: '<span style="color:red">hello</span>'
    }
  },
  computed: {},
  watch: {
    searchText: {
      immediate: true,
      // watch中不能用箭头函数
      handler: debounce(function(val) {
        this.loadSearchSuggestion(val)
      }, 1000)
    }
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestion(val) {
      try {
        const { data } = await getSuggestion(val)
        console.log(data)
        this.suggestionsList = data.data.options
      } catch (err) {
        this.$toast('获取失败，请重试')
      }
    },
    highLight(text) {
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(
        reg,
        `<span style="color:red">${this.searchText}</span>`
      )
    }
  }
}
</script>

<style lang="less" scoped></style>
